﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace NRemedy.MVC.UI
{
    public static class StringExtension
    {
        public static string ToHtmlSafeString(this String src)
        {
            return HttpUtility.HtmlEncode(src);
        }

        //http://www.ibm.com/developerworks/cn/web/wa-lo-json/
        public static string ToSafeJsonString(this String s)
        {
            StringBuilder sb = new StringBuilder(s.Length + 20);
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\"");
                        break;
                    case '\\':
                        sb.Append("\\\\");
                        break;
                    case '/':
                        sb.Append("\\/");
                        break;
                    case '\b':
                        sb.Append("\\b");
                        break;
                    case '\f':
                        sb.Append("\\f");
                        break;
                    case '\n':
                        sb.Append("\\n");
                        break;
                    case '\r':
                        sb.Append("\\r");
                        break;
                    case '\t':
                        sb.Append("\\t");
                        break;
                    default:
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString();
        }


        /// <summary>
        /// support key word $USER$\$GROUPS$\$SERVERTIMESTAMP$
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToARKeyWordDecoded(this String s,SessionController controller)
        {
            string username = controller.ARUserSession.ARContext.User ;
            
            string groups = ";";
            if(controller.ARUserSession.GroupList != null)
            {
                foreach (var g in controller.ARUserSession.GroupList)
                {
                    groups += g + ";";
                }
            }

            string dt = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            return s.Replace("$\\USER$", "\"" + username + "\"")
                .Replace("$\\GROUPS$", "\"" + groups + "\"")
                .Replace("$\\SERVERTIMESTAMP$", "\"" + dt + "\"");

        }
    }
}
